package com.stylefeng.guns.modular.yjya.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.persistence.dao.ContactGroupMapper;
import com.stylefeng.guns.common.persistence.model.Contact;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.yjya.dao.ContactDao;
import com.stylefeng.guns.modular.yjya.dao.ContactGroupDao;
import com.stylefeng.guns.modular.yjya.service.IContactGroupService;
import com.stylefeng.guns.modular.yjya.service.IContactService;
import com.stylefeng.guns.modular.yjya.warpper.ContactWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 通讯录控制器
 *
 * @author xuziyang
 * @Date 2017-12-26 10:38:39
 */
@Controller
@RequestMapping("/contact")
public class ContactController extends BaseController {

    private String PREFIX = "/yjya/contact/";

    private String PREFIXREPORTCONTACTSEL = "/yjya/accident/";

    @Autowired
    private IContactService contactService;

    @Autowired
    private IContactGroupService iContactGroupService;
    @Autowired
    private ContactGroupMapper contactGroupMapper;
    @Autowired
    private ContactDao contactDao;
    @Autowired
    private ContactGroupDao contactGroupDao;



    /**
     * 跳转到通讯录首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "contact.html";
    }

    /**
     * 跳转到生成报告通信录选择页面
     */
    @RequestMapping("/contactSelIndex")
    public String contactSelIndex() {
        return PREFIXREPORTCONTACTSEL + "contactSel.html";
    }

    /**
     * 跳转编辑短信页面
     */
    @RequestMapping("/contactShortMessage")
    public String contactShortMessage() {
        return PREFIXREPORTCONTACTSEL + "edit_short_message.html";
    }

    /**
     * 跳转编辑短信页面
     */
    @RequestMapping("/contactTelphone")
    public String contactTelphone(@RequestParam(value="tel")String tel,Model model) {
        model.addAttribute("tel",tel);
        return PREFIXREPORTCONTACTSEL + "contact_telphone.html";
    }

    /**
     * 汇报上下级弹出页面显示
     */
    @RequestMapping("/all")
    public String all() {
        return PREFIX + "contactAll.html";
    }

    /**
     * 跳转到添加通讯录
     */
    @RequestMapping("/contact_add")
    public String contactAdd() {
        return PREFIX + "contact_add.html";
    }

    @RequestMapping("/contact_sel")
    public String contactSel() {
        return PREFIX + "contact_sel.html";
    }


    @RequestMapping("/contact_sel_admin")
    public String contactSelAdmin() {
        return PREFIX + "contact_sel_admin.html";
    }

    /**
     * 跳转到修改通讯录
     */
    @RequestMapping("/contact_update/{contactId}")
    public String contactUpdate(@PathVariable Integer contactId, Model model) {
        Contact contact = contactService.selectById(contactId);
        model.addAttribute("item",contact);
        String groupName = "";
        if (contact.getGroupId() == 0) {
            groupName = "顶级";
        } else {
            groupName = iContactGroupService.selectById(contact.getGroupId()).getName();
        }
        model.addAttribute("groupName", groupName);
        LogObjectHolder.me().set(contact);
        return PREFIX + "contact_edit.html";
    }

    /**
     * 生成报告时选择添加通讯录人员
     */
    @RequestMapping(value = "/reportContactSel")
    @ResponseBody
    public Object reportContactSel(@RequestParam(value = "groupId",required = false) Integer groupId,
                       @RequestParam(value = "name",required = false) String name,@RequestParam(value = "administrationDuty",required = false) String administrationDuty) {
        Page<Contact> page = new PageFactory<Contact>().defaultPage();
        List<Map<String,Object>> mapList = contactDao.selectContacts(page,name,groupId,administrationDuty);
        page.setRecords((List<Contact>) new ContactWarpper(mapList).warp());
        return super.packForBT(page);
    }

    /**
     * 生成报告时选择添加通讯录人员
     */
    @RequestMapping(value = "/MessageContactSel")
    @ResponseBody
    public Object messageContactSel(@RequestParam(value = "groupId",required = false) Integer groupId,
                                   @RequestParam(value = "name",required = false) String name,@RequestParam(value = "administrationDuty",required = false) String administrationDuty) {
        List<Map<String,Object>> mapList = contactDao.selectContactsNotPage(name,groupId,administrationDuty);
        return new ContactWarpper(mapList).warp();
    }

    /**
     * 添加通讯录人员到报告
     */
    @RequestMapping(value = "/reportContactSelAdd")
    @ResponseBody
    public Object delete(@RequestParam String contactIds) {
        List<Contact> contactList = new ArrayList<>();
        List<String> contactIdsList = Arrays.asList(contactIds.split(","));
        for(int i =0;i<contactIdsList.size();i++){
            Contact contact = contactService.selectById(contactIdsList.get(i));
            contactList.add(contact);
        }
        return contactList;
    }

    /**
     * 获取通讯录列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "groupId",required = false) Integer groupId,
                       @RequestParam(value = "name",required = false) String name,@RequestParam(value = "administrationDuty",required = false) String administrationDuty) {
        Page<Contact> page = new PageFactory<Contact>().defaultPage();
        List<Map<String,Object>> mapList = contactDao.selectContacts(page,name,groupId,administrationDuty);
        page.setRecords((List<Contact>) new ContactWarpper(mapList).warp());
        return super.packForBT(page);
    }

    /**
     * 新增通讯录
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Contact contact) {
        contactService.insert(contact);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除通讯录
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer contactId) {
        contactService.deleteById(contactId);
        return SUCCESS_TIP;
    }

    /**
     * 修改通讯录
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Contact contact) {
        contactService.updateById(contact);
        return super.SUCCESS_TIP;
    }

    /**
     * 通讯录详情
     */
    @RequestMapping(value = "/detail/{contactId}")
    @ResponseBody
    public Object detail(@PathVariable("contactId") Integer contactId) {
        return contactService.selectById(contactId);
    }

    /**
     * 通讯录电话选择
     */
    @RequestMapping("/selectCall")
    public String selectCall() {
        return  "/yjya/accident/contactCallSel.html";
    }

    /**
     * 通讯录电话选择
     */
    @RequestMapping("/selectMessage")
    public String selectMessage() {
        return  "/yjya/accident/contactMessageSel.html";
    }

    /**
     * 通讯录选择
     */
    @RequestMapping("/select")
    public String select() {
        return  "/yjya/counterplanTemplate/counterplan/contact_select.html";
    }

    /**
     * 通讯录上传
     */
    @RequestMapping(value = "/selected")
    @ResponseBody
    public void detail(HttpServletRequest request) {

        System.out.print(request.getParameter("delitems"));
    }

    /**
     * 信息编辑
     */
    @RequestMapping("/editor_info")
    public String editorIndo() {
        return PREFIX + "editor_info.html";
    }

    /**
     导出Excel模板
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response
            ,  ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "通讯录");
        modelMap.put(NormalExcelConstants.CLASS, Contact.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("通讯录列表", "导出人:" + ShiroKit.getUser().getName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }

    /**
     * 上传
     * @param multipartHttpServletRequest
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST,path = "/importExcel")
    @ResponseBody
    public String importExcel(MultipartHttpServletRequest multipartHttpServletRequest, HttpServletResponse response)throws Exception{
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        for(Map.Entry<String,MultipartFile> entity : fileMap.entrySet()){
            MultipartFile multipartFile = entity.getValue(); //获取上传文件对象
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(2);
            importParams.setHeadRows(1);
            importParams.setNeedSave(true);
            List <Contact> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(),Contact.class,importParams);
            for(int i = 0;i<list.size();i++){
                int contactGroupId = contactGroupMapper.selectByName(list.get(i).getGroupName());
                list.get(i).setGroupId(contactGroupId);
            }
            contactService.insertBatch(list);
            multipartFile.getInputStream().close();

        }
        return "文件导入成功";
    }



}
